package com.netty.java.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 *  Socket client
 */
@Slf4j
public class SocketClient {

    private static final String SERVER_HOST = "127.0.0.1";

    private static final int SERVER_PORT = 8888;

    public static void main(String[] args){

        Socket client = null;

        try {

            client = new Socket(SERVER_HOST, SERVER_PORT);

            log.info("Socket Client started");

            PrintWriter writer = new PrintWriter(client.getOutputStream());

            writer.print("what time is it now?");

            writer.flush();

            log.info("发送消息成功！");

            InputStream reader = client.getInputStream();

            byte[] buf = new byte[1024];

            int len = 0;

            StringBuilder sb = new StringBuilder();

            while ((len = reader.read(buf)) != -1){
                sb.append(new String(buf, 0, len));
            }

            String message = sb.toString();

            log.info("Client receive message:[{}]", message);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


}
